/**
 * 自定义工具类和公共配置
 */
//layui模块的定义
;layui.define(["jquery", "layer","myStorage","myApi"], function(exports) {
	/*layui模块申明*/
	var jquery = layui.jquery,myStorage=layui.myStorage,myApi=layui.myApi,layer = layui.layer;
	/**允许跨域*/
	jquery.support.cors = true;
	
	var myUtil = {
			
		/**
		 * 获取值
		 * @param {Object} datas
		 * @param {Object} field
		 */
		getValue : function (datas, field) {
			if(!datas) {
				console.log('datas is empty.');
				return void 0;
			}
			if(!field || field == '') {
				console.log('field is empty.');
				return void 0;
			}
			var index = field.indexOf(".");
			if(index == -1) {
				return datas[field];
			} else {
				var field_ = field.substring(0, index);
				if(field_ == '.') {
					console.log(field + ' start with "."');
					return void 0;
				}
				datas = datas[field_];
				field = field.substring(index + 1, field.length);
				
				var type = typeof datas;
				if(type != 'object') {
					console.log("current value [" + datas + "], type [" + type + "] can not get value with key [" + field + "]");
					return void 0;
				}
				
				return myUtil.getValue(datas, field);
			}
		},
			
		/**
		 * 蓝色提示
		 * @param {Object} content
		 * @param {Object} selector
		 * @param {Object} time
		 */
		blueTips : function (content, selector, time) {
			time = time || 1500;
			layer.tips(content, selector, {tips: [2, '#3595CC'],time: time});
		},
		
		showDisplay : function(name, code){
			if(name && name != '' && code && code != '') {
				return name + '[' + code + ']';
			} else if(name && name != '') {
				return name;
			} else if(code && code != ''){
				return code;
			} else {
				return '';
			}
		},
		
		/**
		 * 展示数据
		 */
		show : function(data, defaultValue) {
			if(data == undefined || data == null || data == ''){
				return defaultValue ? defaultValue : '-';
			} else {
				return data;
			}
		},
		
		/**
		 * 整数
		 */
		showInt : function(a){
			if((a && a != '') || a == 0) {
				return a.toFixed(0);
			} else {
				return '-';
			}
		},
		
		/**
		 * 两位小数点
		 */
		showNumber : function(a,scale){
			scale = scale || 2;
			if((a && a != '') || a == 0) {
				return a.toFixed(scale);
			} else {
				return '-';
			}
		},
		
		/**
		 * 百分比
		 */
		showPrecentNumber : function(a, scale){
			scale = scale || 2;
			if((a && a != '') || a == 0) {
				return (a * 100).toFixed(scale);
			} else {
				return '-';
			}
		},
		
		/**
		 * 单位为万
		 */
		showBigNumber :function(a){
			scale = scale || 2;
			if((a && a != '') || a == 0) {
				return (a / 10000).toFixed(scale);
			} else {
				return '-';
			}
		},
		
		/**
		 * 格式化时间
		 * @param {Object} date 时间
		 */
		formatDateToMinute:function(date) {
			if(!a || a == '') {
				return '-';
			}
			return myUtil.formatDate(date,'yyyy-MM-dd HH:mm');
		},
		
		/**
		 * 日期格式化
		 * @param {Object} date 时间 可以为date，string，integer
		 * @param {Object} fmt 格式
		 * @param {Object} today 默认今天 true/false
		 */
		formatDate : function(date, fmt, today){
			if((!date || date == '') && today) {
				date = new Date();
			}
			if(!date || date == '') {
				console.log('date [' + date + '] is empty.');
				return '-'; //没有值
			}
			if(!fmt || fmt == '') {
				fmt = 'yyyy-MM-dd HH:mm:ss';
			}
			//判断的次序不能变更Date>Number>String (Date属于Number,Number属于String)
			if(myUtil.isType(date,'Date')){
				//不需要转
			} else if(date.length != 4 && myUtil.isType(date,'Number')) {
				date = new Date(date * 1000); //unix时间戳,注意不要输入格式为数字的格式化数据
			} else if(myUtil.isType(date,'String')) {
				var re = new RegExp("^(\\d{4})([-\/](\\d{1}|0\\d{1}|1[0-2])([-\/](\\d{1}|0\\d{1}|[1-2][0-9]|3[0-1])(\\s(\\d{1}|0\\d{1}|1\\d|2[0-4])(:[0-5]?\\d(:[0-5]?\\d)?)?)?)?)?$");
				if(!re.test(date)) {//错误的时间
					console.log('date [' + date + '] is not corret.');
					if(today) { 
						date = new Date();	
					} else {
						return '';
					}
				} else {
					var dates_ = date.split(/[-\/:\s]+/);
					var length = dates_.length
					if(length == 1) {
						date = new Date(dates_[0], 0, 1);
					} else if(length == 2){
						date = new Date(dates_[0], dates_[1] - 1, 1);
					} else if(length == 3){
						date = new Date(dates_[0], dates_[1] - 1, dates_[2]);
					} else if(length == 4){
						date = new Date(dates_[0], dates_[1] - 1, dates_[2], dates_[3], 0, 0);
					} else if(length == 5){
						date = new Date(dates_[0], dates_[1] - 1, dates_[2], dates_[3], dates_[4], 0);
					} else if(length == 6){
						date = new Date(dates_[0], dates_[1] - 1, dates_[2], dates_[3], dates_[4], dates_[5]);
					} else { //错误
						console.log('date [' + date + '] is not corret.');
						if(today) { 
							date = new Date();	
						} else {
							return '';
						}
					}
				}
			} else {
				console.log('date [' + date + '] is not corret.');
				if(today) {
					date = new Date();
				} else {
					return '';
				}
			}
    		
			var o = {
		        "M+" : date.getMonth() + 1,
		        "d+" : date.getDate(),
		        "H+" : date.getHours(),
		        "m+" : date.getMinutes(),
		        "s+" : date.getSeconds(),
		        "q+" : Math.floor((date.getMonth() + 3) / 3),
		        "S" : date.getMilliseconds()
	    	};
	    	if (/(y+)/.test(fmt)) {
	    		var y = date.getFullYear();
	    		fmt = fmt.replace(RegExp.$1, (y + "").substr(4 - RegExp.$1.length));
	    	}
	    	for (var k in o) {
	    		if (new RegExp("(" + k + ")").test(fmt)) {
	    			 fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	    		}
	    	}
	    	return fmt;
		},
		
		/*uuid*/
		guid : function() {
		 	  function S4() {
		 	    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
		 	  }
		 	  return S4()+S4()+S4()+S4()+S4()+S4()+S4()+S4();
		},
		
		//计算天数差的函数，通用
		dateDiff : function(sDate1){
		    var  aDate,  oDate1,  iDays  
		    aDate  =  sDate1.split("-")  
		    oDate1  =  new  Date(aDate[1]  +  '-'  +  aDate[2].split(" ")[0]  +  '-'  +  aDate[0]) //转换为12-18-2006格式  
		    
		    sDate2  =  new  Date(); 
		    var year2 = sDate2.getFullYear();
		    var month2 = sDate2.getMonth() + 1;
		    var day2 = sDate2.getDate();
		    var oDate2 = new  Date(month2 + '-' + day2 + '-' + year2 );
		    
		    var diffDate = (oDate1  -  oDate2)  /  1000  /  60  /  60  /24;//把相差的毫秒数转换为天数  
		    var iDays  =  parseInt(diffDate);
		    if(iDays > 0){
		    	return iDays;
		    } else if(iDays < 0){
		    	return '<span style="color:red;">已超期'+  Math.abs(iDays) + '天</span>';
		    } else {
		    	return '<span style="color:red;">今日到期</span>';
		    }
		},
		
		/**
		 * 判断对象类型
		 * @param {Object} obj
		 */
		isType : function(obj, type) { 
			return (type === "Null" && obj === null) || 
				(type === "Undefined" && obj === void 0 ) || 
				(type === "Number" && isFinite(obj)) || 
				Object.prototype.toString.call(obj).slice(8,-1) === type; 
		},
		/**
		 * 判断文件是否存在
		 * @param url 文件路径
		 */
		fileExists : function(url) {
			var xmlHttp;
			if (window.ActiveXObject) {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} else if (window.XMLHttpRequest) {
				xmlHttp = new XMLHttpRequest();
			}
			xmlHttp.open("Get", url, false);
			xmlHttp.send();
			if (xmlHttp.status == 404) {
				return false;
			} else {
				return true;
			}
		},
		isIE : function() {
		    if (!!window.ActiveXObject || "ActiveXObject" in window) { 
		    	return true;  
			} else {
				return false; 
			}
		},
		/**                                     101214 
		 * 匹配并标识         序号:0 1 2 3 456789 111315    
		 * @param data 数据  例子：行政部门[0001000001]
		 * @param value 匹配值 例子：00
		 * @param ignoreCase 是否忽略大小写
		 * return 行政部门[<span style="color:red;">000</span>1<span style="color:red;">00000</span>1]   
		 */
		matchAndSign : function(data, value, ignoreCase) {
			data = data || '';
			if(!value || value == '') {
				return data;
			}
			ignoreCase = (ignoreCase === false ? false : true);
			
			//查找出所有位置
			var indexs = []; // 5,6,9,10,11,12
			var tmpData = ignoreCase ? data.toLocaleLowerCase() : data;
			var tmpValue = ignoreCase ? value.toLocaleLowerCase() : value;
			var index = 0;
			var valueLength = value.length;
			while(index < tmpData.length) {
				var tmpIndex = tmpData.indexOf(tmpValue, index);
				if(tmpIndex >= 0) {
					indexs.push(tmpIndex);
					index = tmpIndex + 1;
				} else {
					break;
				}
			}
			var startFlag = '<span style="color:red;">';
			var endFlag = '</span>';
			var step = valueLength;
			var datas = [];
			for(var i = 0; i < indexs.length; i++) {
				if(i == 0 && indexs[i] == 0) {
					datas.push(startFlag);
					if(i == indexs.length - 1) {
						datas.push(data.substring(indexs[i], indexs[i] + valueLength));
						datas.push(endFlag);
						datas.push(data.substring(indexs[i] + valueLength, data.length));
					}
				} else if(i == 0 && indexs[i] != 0) {
					datas.push(data.substring(0, indexs[i]));
					datas.push(startFlag);
					if(i == indexs.length - 1) {
						datas.push(data.substring(indexs[i], indexs[i] + valueLength));
						datas.push(endFlag);
						datas.push(data.substring(indexs[i] + valueLength, data.length));
					}
				} else if(indexs[i] > indexs[i-1] + step && i != indexs.length - 1) {
					datas.push(data.substring(indexs[i-1], indexs[i-1] + valueLength));
					datas.push(endFlag);
					datas.push(data.substring(indexs[i-1] + valueLength, indexs[i]));
					datas.push(startFlag);
				} else if(indexs[i] <= indexs[i-1] + step && i != indexs.length - 1) {
					datas.push(data.substring(indexs[i-1], indexs[i]));
				} else if(indexs[i] > indexs[i-1] + step && i == indexs.length - 1) {
					datas.push(data.substring(indexs[i-1], indexs[i-1] + valueLength));
					datas.push(endFlag);
					datas.push(data.substring(indexs[i-1] + valueLength, indexs[i]));
					datas.push(startFlag);
					datas.push(data.substring(indexs[i], indexs[i] + valueLength));
					datas.push(endFlag);
					datas.push(data.substring(indexs[i] + valueLength, data.length));
				} else if(i == indexs.length - 1){ //最后一个
					datas.push(data.substring(indexs[i-1], indexs[i]));
					datas.push(data.substring(indexs[i], indexs[i] + valueLength));
					datas.push(endFlag);
					datas.push(data.substring(indexs[i] + valueLength, data.length));
				}
			}
			datas = datas.join("");
			return datas;
		}
	}
	
	exports('myUtil', myUtil);
});